
/*
This file is part of MJIN2.

Copyright (C) 2012-2013 Opensource Game Studio

This software is provided 'as-is', without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include <mjin2/SceneNode.h>
#include <mjin2/priv/SceneNode.h>

namespace mjin2
{
namespace priv
{

SceneNode::SceneNode(const String &name) throw ()
{
    mScale = Vec3(1, 1, 1);
    mNode = new osg::MatrixTransform;
    mNode->setName(name);
    // Do not cast shadow by default.
    mNode->setNodeMask(0x1);
}

SceneNode::~SceneNode() throw ()
{
    removeAndDestroyAllChildren();
}

void SceneNode::addChild(mjin2::SceneNode *n) throw (Exception)
{
    mNode->addChild(n->mD->mNode);
    mChildren.push_back(n);
}

mjin2::SceneNode *SceneNode::child(const String &name) throw (Exception)
{
    for (auto it = mChildren.begin(); it != mChildren.end(); ++it)
        if ((*it)->name() == name)
            return *it;
    MJIN2_EXCEPTION("Invalid scene node",
                    MJIN2_STR("SceneNode '%s' of SceneNode '%llu' cannot be "
                              "found", name.c_str(), this));
}

String SceneNode::name() const throw ()
{
    return mNode->getName();
}

Vec3 SceneNode::position() const throw ()
{
    osg::Vec3d p = mNode->getMatrix().getTrans();
    return Vec3(p.x(), p.y(), p.z());
}

Vec3 SceneNode::positionAbs() const throw ()
{
    osg::Vec3d p =
        osg::computeLocalToWorld(mNode->getParentalNodePaths()[0]).getTrans();
    return Vec3(p.x(), p.y(), p.z());
}

void SceneNode::removeAndDestroyAllChildren() throw ()
{
    for (auto it = mChildren.begin(); it != mChildren.end(); ++it)
    {
        // Prevent uncontrolled dereferencing.
        //(*it)->mNode->ref();
        mNode->removeChild((*it)->mD->mNode);
        delete *it;
    }
    mChildren.clear();
}

void SceneNode::removeChild(mjin2::SceneNode *n) throw (Exception)
{
    for (auto it = mChildren.begin(); it != mChildren.end(); ++it)
        if (*it == n)
        {
            // Prevent uncontrolled dereferencing.
            //n->mNode->ref();
            mNode->removeChild(n->mD->mNode);
            mChildren.erase(it);
            return;
        }
    MJIN2_EXCEPTION("Invalid scene node",
                    MJIN2_STR("SceneNode '%llu' cannot be removed from SceneNode '%llu', "
                              "because it is not found", n, this));
}

void SceneNode::parentOrientationChanged() throw ()
{
    for (auto it = mChildren.begin(); it != mChildren.end(); ++it)
        (*it)->mD->parentOrientationChanged();
}

Vec4 SceneNode::rotation() const throw ()
{
    osg::Vec3d translation;
    osg::Quat q;
    osg::Vec3d scale;
    osg::Quat so;
    mNode->getMatrix().decompose(translation, q, scale, so);
    return Vec4(q.x(), q.y(), q.z(), q.w());
}

Vec4 SceneNode::rotationAbs() const throw ()
{
    osg::Vec3d translation;
    osg::Quat q;
    osg::Vec3d scale;
    osg::Quat so;
    osg::computeLocalToWorld(mNode->getParentalNodePaths()[0]).decompose(
            translation, q, scale, so);
    return Vec4(q.x(), q.y(), q.z(), q.w());
}

void SceneNode::setPosition(const Vec3 &pos) throw ()
{
    osg::Matrix m = mNode->getMatrix();
    Vec4 rot = rotation();
    mNode->setMatrix(
        osg::Matrix::scale(osg::Vec3d(mScale.x, mScale.y, mScale.z)) *
        osg::Matrix::rotate(osg::Quat(rot.x, rot.y, rot.z, rot.w)) *
        osg::Matrix::translate(osg::Vec3d(pos.x, pos.y, pos.z)));
    parentOrientationChanged();
}

Vec3 SceneNode::scale() const throw ()
{
    return mScale;
}

void SceneNode::setRotation(const Vec4 &rot) throw ()
{
    osg::Matrix m = mNode->getMatrix();
    mNode->setMatrix(
        osg::Matrix::scale(osg::Vec3d(mScale.x, mScale.y, mScale.z)) *
        osg::Matrix::rotate(osg::Quat(rot.x, rot.y, rot.z, rot.w)) *
        osg::Matrix::translate(m.getTrans()));
    parentOrientationChanged();
}

void SceneNode::setScale(const Vec3 &scale) throw ()
{
    mScale = scale;
    osg::Matrix m = mNode->getMatrix();
    mNode->setMatrix(
        osg::Matrix::scale(osg::Vec3d(mScale.x, mScale.y, mScale.z)) *
        osg::Matrix::rotate(m.getRotate()) *
        osg::Matrix::translate(m.getTrans()));
    // Re-calculate normals.
    mNode->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
}

} // namespace priv
} // namespace mjin2

